package com.itheima.reggie.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Integer update(Employee employee) {
       Integer updateNum =  employeeMapper.update(employee);
        return updateNum;
    }

    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        return employee;
    }

    @Override
    public ResultInfo add(Employee employee) {
        Integer addNUm = employeeMapper.add(employee);
        return addNUm > 0 ? ResultInfo.success(null) : ResultInfo.error("添加失败，请稍候再试");
    }

    @Override
    public ResultInfo login(String username, String password) {
        Employee employee = employeeMapper.findByUsername(username);

        //判断根据username是否能够查出来
        if (employee == null){
            return ResultInfo.error("查无此人");
        }
        //判断密码是否匹配
        // SecureUtil.md5 MD5加密
        //StringUtils.equals  对比字符串是否相等
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(employee.getPassword(),passwordWithMd5)){
            return ResultInfo.error("密码不正确");
        }
        //判断状态是否启用
        if (employee.getStatus() == Employee.STATUS_DISABLE){
            return  ResultInfo.error("当前用户已禁用");
        }

        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
       List<Employee> employeeList =  employeeMapper.findByName(name);
        return employeeList;
    }
}
